package org.mytools.util;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class HttpUtils {

	public static Document getHtmlDocument(String url) {
		return getHtmlDocument(url, 6000, null, null, null, null);
	}

	public static Document getHtmlDocument(String url, int timeout) {
		return getHtmlDocument(url, timeout, null, null, null, null);
	}

	public static Document getHtmlDocument(String url, int timeout,
			String referrer) {
		return getHtmlDocument(url, timeout, referrer, null, null, null);
	}

	public static Document getHtmlDocument(String url, int timeout,
			String referrer, Map<String, String> header) {
		return getHtmlDocument(url, timeout, referrer, header, null, null);
	}

	public static Document getHtmlDocument(String url, int timeout,
			String referrer, Map<String, String> header,
			Map<String, String> cookie) {
		return getHtmlDocument(url, timeout, referrer, header, cookie, null);
	}

	/**
	 * get HTML document
	 * 
	 * @param url
	 *            : request URL
	 * @param timeout
	 *            : request timeout
	 * @param referrer
	 *            :request host
	 * @param header
	 *            : request header
	 * @param cookie
	 *            :request cookie
	 * @param data
	 *            :request data
	 * @return
	 */
	public static Document getHtmlDocument(String url, int timeout,
			String referrer, Map<String, String> header,
			Map<String, String> cookie, Map<String, String> data) {
		Document doc = null;
		Connection connection = Jsoup.connect(url).timeout(timeout);
		try {
			// set request host
			if (null != referrer) {
				connection = Jsoup.connect(url).referrer(referrer);
			}
			// set request header
			Set<String> headerKeys = (null == header) ? new HashSet<String>()
					: header.keySet();
			for (String key : headerKeys) {
				connection = connection.header(key, header.get(key));
			}
			// set request cookie
			Set<String> cookieKeys = (null == cookie) ? new HashSet<String>()
					: cookie.keySet();
			for (String key : cookieKeys) {
				connection = connection.header(key, cookie.get(key));
			}
			// set request data
			if (null != data) {
				connection = connection.data(data);
			}
			// send get request
			doc = connection.get();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return doc;
	}

}
